package pers.cz.chat.utils;

import pers.cz.chat.model.dto.InnerCmdMessage;
import pers.cz.chat.model.dto.JefColor;


/**
 * @version 1.0
 * @description:
 * @author: ChengZhi 0336
 * @create: 2025-01-13 19:24
 **/
public class LogUtils {


	private static final String DELIM_STR = "{}";
	public static void print(JefColor jefColor, String msg, Object... objects){
		InnerCmdMessage innerCmdMessage = new InnerCmdMessage();
		innerCmdMessage.setJefColor(jefColor);
		innerCmdMessage.setMessage(format(msg, objects));
		System.out.println(JsonUtils.toJson(innerCmdMessage));
	}

	public static void printWarn(String msg) {
		System.out.println("\u001B[31m" + msg + "\u001B[0m");
	}

	public static void printMessage(JefColor jefColor, String title, Object... objects) {
		print(jefColor, title, objects);
	}

	public static String format(String messagePattern, Object... argArray) {
		return arrayFormat(messagePattern, argArray);
	}

	private static String arrayFormat(final String messagePattern, final Object[] argArray) {

		int i = 0;
		int j;
		StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
		int L;
		// 拼接消息
		for (L = 0; L < argArray.length; L++) {
			j = messagePattern.indexOf(DELIM_STR, i);
			if (j == -1) {
				// 判断最后一个是否为Throwable
				Object lastArg = argArray[argArray.length - 1];
				if (lastArg instanceof Throwable) {
					if (i == 0) {
						sbuf.append(messagePattern);
						sbuf.append(": ");
						return sbuf.append(((Throwable) lastArg).getMessage()).toString();
					} else {
						sbuf.append(", ");
						sbuf.append(((Throwable) lastArg).getMessage());
						return sbuf.toString();
					}
				}
				return messagePattern;
			} else {
				// 截取
				sbuf.append(messagePattern, i, j);
				sbuf.append(argArray[L]);
				i = j + 2;
			}
		}
		sbuf.append(messagePattern, i, messagePattern.length());
		return sbuf.toString();
	}
}
